#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
下载 Cubism 2.1 运行时库 (live2d.min.js)
"""

import urllib.request
import os
from pathlib import Path

def download_file(url, dest_path, file_name):
    """下载文件并显示进度"""
    print(f"\n正在下载 {file_name}...")
    print(f"URL: {url}")
    
    try:
        # 创建请求
        req = urllib.request.Request(
            url,
            headers={
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        )
        
        # 下载文件
        with urllib.request.urlopen(req, timeout=60) as response:
            total_size = int(response.headers.get('Content-Length', 0))
            downloaded = 0
            
            # 写入文件
            with open(dest_path, 'wb') as f:
                while True:
                    chunk = response.read(8192)
                    if not chunk:
                        break
                    f.write(chunk)
                    downloaded += len(chunk)
                    
                    if total_size > 0:
                        progress = (downloaded / total_size) * 100
                        print(f"\r进度: {progress:.1f}% ({downloaded}/{total_size} bytes)", end='')
        
        print(f"\n✓ {file_name} 下载完成!")
        return True
        
    except Exception as e:
        print(f"\n✗ 下载失败: {e}")
        return False

def main():
    # 创建 libs 目录
    libs_dir = Path(__file__).parent / 'libs'
    libs_dir.mkdir(exist_ok=True)
    
    print("=" * 70)
    print("下载 Cubism 2.1 运行时库")
    print("=" * 70)
    
    # Cubism 2.1 运行时的多个备用下载源
    sources = [
        {
            'name': 'GitHub CDN (dylanNew)',
            'url': 'https://cdn.jsdelivr.net/gh/dylanNew/live2d/webgl/Live2D/lib/live2d.min.js',
            'filename': 'live2d.min.js'
        },
        {
            'name': 'GitHub 原始文件',
            'url': 'https://raw.githubusercontent.com/dylanNew/live2d/master/webgl/Live2D/lib/live2d.min.js',
            'filename': 'live2d.min.js'
        },
        {
            'name': 'Fastly CDN',
            'url': 'https://fastly.jsdelivr.net/gh/dylanNew/live2d/webgl/Live2D/lib/live2d.min.js',
            'filename': 'live2d.min.js'
        },
    ]
    
    dest_path = libs_dir / 'live2d.min.js'
    
    # 如果文件已存在,先备份
    if dest_path.exists():
        backup_path = libs_dir / 'live2d.min.js.backup'
        print(f"\n备份现有文件到: {backup_path}")
        os.replace(dest_path, backup_path)
    
    # 尝试每个下载源
    success = False
    for source in sources:
        print(f"\n尝试从 {source['name']} 下载...")
        if download_file(source['url'], dest_path, source['name']):
            success = True
            break
        print("该源失败,尝试下一个源...")
    
    if success:
        # 验证文件
        file_size = dest_path.stat().st_size
        print("\n" + "=" * 70)
        print("✓ 下载成功!")
        print(f"文件大小: {file_size:,} bytes")
        print(f"保存路径: {dest_path.resolve()}")
        
        # 检查文件内容
        with open(dest_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read(100)
            if 'Live2D' in content or 'live2d' in content.lower():
                print("✓ 文件内容验证通过!")
            else:
                print("⚠ 警告: 文件内容可能不正确")
                print(f"文件开头: {content[:50]}")
        
        print("=" * 70)
    else:
        print("\n" + "=" * 70)
        print("✗ 所有下载源都失败了!")
        print("\n手动下载说明:")
        print("1. 访问: https://github.com/dylanNew/live2d")
        print("2. 下载文件: webgl/Live2D/lib/live2d.min.js")
        print(f"3. 保存到: {dest_path.resolve()}")
        print("=" * 70)
        
        # 恢复备份
        backup_path = libs_dir / 'live2d.min.js.backup'
        if backup_path.exists():
            print("\n恢复备份文件...")
            os.replace(backup_path, dest_path)

if __name__ == '__main__':
    main()
